import './menu.css'
import {
  findCurrentMenu,
  parseJSON,
  toggleMenu,
  iconArrow,
  isCurrentPath,
  getCurrentPath
} from './utils.js'

// 生成主体HTML
function generateHTML(id) {
  const menus = parseJSON(window.localStorage.getItem('wanxiang_data_menu')) || []
  const div = document.createElement('div')
  let currentPath = window.localStorage.getItem('wanxiang_current_path')
  let expandMenus = parseJSON(window.localStorage.getItem('wanxiang_expand_menus')) || []
  let position = window.localStorage.getItem('wanxiang_scroll_position')

  if (!isCurrentPath(currentPath)) {
    const [cur, exp] = getCurrentPath(menus)
    currentPath = cur
    expandMenus = exp
    position = null
  }

  document.body.appendChild(div)
  div.outerHTML = `<div class="wanxiang-flex-column">
  <div class="wanxiang-header">万象，微前端解决方案</div>
  <div class="wanxiang-flex">
    <div class="wanxiang-menu" id="__wanxiang_menu">
      ${generateMenu(menus, expandMenus, currentPath)}
    </div>
    <div class="wanxiang-container" id="__wanxiang_container"></div>
  </div>
</div>`

  document.getElementById('__wanxiang_container').appendChild(document.querySelector(id))

  if (position) {
    const [x, y] = position.split(',')
    document.getElementById('__wanxiang_menu').scrollTo(x, y)
  }
}

// 绑定菜单事件
function bindMenuEvents() {
  const menuDiv = document.getElementById('__wanxiang_menu')
  // 点击
  menuDiv.addEventListener('click', e => {
    const current = findCurrentMenu(e)
    if (current) {
      if (current.dataset.path) {
        for (let m of menuDiv.querySelectorAll('.wanxiang-menu-item')) {
          m.classList.remove('wanxiang-menu-current')
        }
        current.parentElement.classList.add('wanxiang-menu-current')

        // 路由跳转
        window.localStorage.setItem('wanxiang_current_path', current.dataset.path)
        window.location.href = current.dataset.path
      } else {
        // 展开或收起子菜单
        toggleMenu(current)
      }
    }
  })

  // 记录滚动结束位置
  menuDiv.addEventListener('scrollend', e => {
    window.localStorage.setItem(
      'wanxiang_scroll_position',
      `${e.target.scrollLeft},${e.target.scrollTop}`
    )
  })
}

// 开始
export const start = function(id, callback) {
  generateHTML(id)
  bindMenuEvents()
  callback()
}

// 渲染菜单
function generateMenu(menus, expandMenus, currentPath, level = 1) {
  return menus.map(m => `<div class="wanxiang-menu-item${
    currentPath === m.path ? ' wanxiang-menu-current' : ''
}${
  m.path || expandMenus.includes(m.code) ? '' : ' wanxiang-colsed'
}"${
  m.path ? '' : ' data-code="' + m.code + '"'
}>
  <div class="wanxiang-menu-name" ${
    m.path ? 'data-path=' + m.path : ''
} style="padding-left:${level * 10}px;">
  <span>${m.name}</span>${m.children && m.children.length ? iconArrow() : ''}
</div>
  ${m.children && m.children.length
    ? `<div class="wanxiang-submenu" data-max-height="${m.children.length * 40}px">${
      generateMenu(m.children, expandMenus, currentPath, level + 1)
    }</div>`
    : ''
  }
</div>`).join('')
}

// 设置菜单数据
export const setMenus = function(menus) {
  window.localStorage.setItem('wanxiang_data_menu', JSON.stringify(menus))

  let expandMenus = parseJSON(window.localStorage.getItem('wanxiang_expand_menus')) || []
  let currentPath = window.localStorage.getItem('wanxiang_current_path')
  if (!isCurrentPath(currentPath)) {
    const [cur, exp] = getCurrentPath(menus, true)
    currentPath = cur
    expandMenus = exp
  }

  document.getElementById('__wanxiang_menu').innerHTML = generateMenu(menus, expandMenus, currentPath)
}
